-- File(s) --

file.nameExt .file .name .ext :- rightSplit .file "." .name .ext ! #
file.nameExt .file .file "" #

file.getLastMod .filename .time :-
	getTimestampFromCommand ("stat -c %%Y " .filename " 2>&1") .time #

file.exists .filename :-
	command.result ("ls " .filename " >/dev/null 2>&1") 0 #

file.each .pattern .filename :-
	command.line ("ls -1 -d " .pattern " 2>/dev/null") .filename #

file.line .filename .line :-
	stream.readFile .stream .filename,
	stream.line .stream .line;
	stream.close .stream,
	fail #

stream.while .s :- not (stream.eof .s) ! streamWhile2 .s #

streamWhile2 . #
streamWhile2 .s :- not (stream.eof .s) ! streamWhile2 .s #


-- Command(s) --

execute .command :-
	command.format .command .s,
	write "--" .s, nl,
	exec .s 0 #

command.result .command .code :-
	command.format .command .s,
	exec .s .code #

command.lines .command .lines :-
	findall .line (command.line .command .line) .lines #

command.line .command .line :-
	command.format .command .s,
	stream.popen .pipe .s,
	stream.line .pipe .line;
	stream.close .pipe, fail #

command.format .tuple "" :-
	length .tuple 0 ! #
command.format .tuple .s :-
	is.tuple .tuple !
	nth .tuple 0 .first,
	command.format .first .head,
	mnth .tuple 1 0 .remains,
	command.format .remains .tail,
	concat .head .tail .s #
command.format (.first, .remains) .s :- !
	command.format .first .firstC,
	command.format .remains .remainsC,
	concat .firstC " " .remainsC .s #
command.format .elem .s :-
	concat .elem .s #


-- Process(es) --

process.kill .pid :-
	concat "ps --pid " .pid " > /dev/null" .command,
	not (execute .command) ! #
process.kill .pid :-
	concat "kill " .pid .command,
	whatever (execute .command),
	sleep 0.25,
	process.kill .pid # -- Until it's really dead


-- Timestamp(s) --

time.get .time :-
	getTimestampFromCommand "date +%%s" .time #

time.getHMS .time .h .m .s :-
	let .h (.time mod 86400 / 3600),
	let .m (.time mod 3600 / 60),
	let .s (.time mod 60) #

date.get (DATE .year .month .day .hour .min .sec) :-
	stream.popen .pipe "date +%%Y%%m%%d%%H%%M%%S",
	stream.line .pipe .str !
	substr .str 0 4 .Y, let .year .Y,
	substr .str 4 6 .M, let .month .M,
	substr .str 6 8 .D, let .day .D,
	substr .str 8 10 .h, let .hour .h,
	substr .str 10 12 .m, let .min .m,
	substr .str 12 14 .s, let .sec .s,
	stream.close .pipe #

sleep .seconds :-
	concat "sleep " .seconds .command,
	exec .command 0 #


-- Text Coloring --

Black   :- ANSI.Color 30 #
Blue    :- ANSI.Color 34 #
Cyan    :- ANSI.Color 36 #
Green   :- ANSI.Color 32 #
Magenta :- ANSI.Color 35 #
Red     :- ANSI.Color 31 #
White   :- ANSI.Color 37 #
Yellow  :- ANSI.Color 33 #

ANSI.Color .no :-
	ascii .esc 27, concat .esc "[0;" .no "m" .str, put .str #


-- Helpers --

getTimestampFromCommand .command .time :-
	command.lines .command (.str,),
	let .time .str #
